import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:chatgreat/bloc/creative_island_bloc.dart';
import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:clipboard/clipboard.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../helper/helper.dart';
import '../../../repo/api_server.dart';
import '../../helper/event.dart';
import '../../repo/model/mine_collection_model.dart';
import '../component/audio_player.dart';
import '../component/chat/markdown.dart';
import '../component/dialog.dart';

class MyCollectionScreen extends StatefulWidget {
  final SettingRepository setting;

  const MyCollectionScreen({
    super.key,
    required this.setting,
  });

  @override
  State<MyCollectionScreen> createState() => _MyCollectionScreenState();
}

enum GenerateStatus { display, generating, over }

class _MyCollectionScreenState extends State<MyCollectionScreen>
    with TickerProviderStateMixin {
  final TextEditingController _textController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  int page = 1;
  List<CollectionRecord> items = [];

  bool enableNotifier = true;
  bool isReady = false;

  // 音频播放器控制器
  final AudioPlayerController audioPlayerController =
      AudioPlayerController(useRemoteAPI: true);
  int? playingMessageId = 0;
  // 显示音频播放器的状态
  bool showAudioPlayer = false;
  // 是否显示音频播放器加载中
  bool audioLoadding = false;

  @override
  void initState() {
    audioPlayerController.onPlayStopped = () {
      showAudioPlayer = false;
      audioLoadding = false;
      setState(() {});
    };
    audioPlayerController.onPlayAudioStarted = () {
      setState(() {
        showAudioPlayer = true;
      });
    };
    audioPlayerController.onPlayCompletion = () {
      playingMessageId = 0;
      showAudioPlayer = false;
      setState(() {});
    };

    audioPlayerController.onPlayAudioLoading = (loading) {
      setState(() {
        audioLoadding = loading;
      });
    };
    super.initState();

    Future.delayed(const Duration(milliseconds: 700))
        .then((value) => _refreshController.requestRefresh());
  }

  @override
  void dispose() {
    _textController.dispose();
    _scrollController.dispose();
    audioPlayerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: _buildCollectItems(customColors),
        ),
      ),
    );
  }

  /// 我的收藏
  Widget _buildCollectItems(
    CustomColors customColors,
  ) {
    return SliverCreateComponent(
      title: const Text(
        "我的收藏",
        style: TextStyle(
          fontSize: CustomSize.appBarTitleSize,
          color: Colors.white,
        ),
      ),
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back,
          color: customColors.weakLinkColor,
        ),
        onPressed: () {
          if (context.canPop()) {
            audioPlayerController.stop();
            context.pop();

            GlobalEvent().emit('refresh_4');
          }
        },
      ),
      child: buildContentPreviewArea(customColors),
    );
  }

  Widget buildContentPreviewArea(customColors) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(waterDropColor: stringToColor('FF4F6CEF')),
      footer: CustomFooter(builder: (BuildContext context, LoadStatus? mode) {
        Widget body;
        if (mode == LoadStatus.idle) {
          return const SizedBox();
        } else if (mode == LoadStatus.loading) {
          body = const CupertinoActivityIndicator();
        } else if (mode == LoadStatus.failed) {
          body = const Text("加载失败！点击重试！");
        } else if (mode == LoadStatus.canLoading) {
          body = const Text("松手，加载更多！");
        } else {
          body = const Text("没有更多数据了！");
        }
        return SizedBox(
          height: 55.0,
          child: Center(child: body),
        );
      }),
      controller: _refreshController,
      onRefresh: () {
        page = 1;
        _getCollectList();
      },
      onLoading: () {
        page += 1;
        _getCollectList();
      },
      child: items.isNotEmpty ? ListView.builder(
        controller: _scrollController,
        itemBuilder: (c, i) => _itemForRow(items[i], customColors),
        shrinkWrap: true,
        itemCount: items.length,
      ) : NullListWidget('images/no_collect_null_bg.png', '您当前没有收藏'),
    );
  }

  Widget _itemForRow(CollectionRecord record, CustomColors customColors) {
    return Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              margin: const EdgeInsets.fromLTRB(15, 0, 15, 15),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(15),
                      topRight: Radius.circular(15),
                      bottomRight: Radius.circular(15)),
                  color: Colors.white.withOpacity(0.2)),
              child: _buildMessageBox(context, record)),
          Padding(
            padding: const EdgeInsets.only(left: 15, right: 15, bottom: 22),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                //播放
                GestureDetector(
                  onTap: () {
                    if (audioLoadding) {
                      return;
                    }
                    if (showAudioPlayer) {
                      playingMessageId = 0;
                      audioPlayerController.stop();
                    } else {
                      playingMessageId = record.id;
                      audioPlayerController
                          .playAudioWithMessageId(playingMessageId ?? 0);
                    }
                  },
                  child: Row(
                    children: [
                      Container(
                        // width: 65,
                        height: 32,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.white.withOpacity(0.12),
                        ),
                        padding: const EdgeInsets.only(
                            left: 9, right: 9, top: 7, bottom: 7),
                        child: Row(
                          children: [
                            imgWidget(
                                17,
                                17,
                                (showAudioPlayer &&
                                        record.id == playingMessageId)
                                    ? 'play'
                                    : 'stop'),
                            const SizedBox(
                              width: 8.5,
                            ),
                            // gif
                            if (audioPlayerController != null &&
                                record.id == playingMessageId)
                              EnhancedAudioPlayer(
                                controller: audioPlayerController!,
                                loading: audioLoadding,
                              ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                //更多
                Container(
                  height: 32,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.white.withOpacity(0.12),
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          var replacedString = record.content.replaceAll('\\n', '\\\n');
                          replacedString = replacedString.replaceAll('\\', '');
                          FlutterClipboard.copy(replacedString).then((value) {
                            showSuccessMessage('已复制到剪贴板');
                          });
                        },
                        child: Container(
                          color: Colors.transparent,
                            padding: const EdgeInsets.only(right: 2),
                            width: 45,
                            height: 30,
                            child: Center(
                              child: imgWidget(17, 17, 'copy'),
                            )),
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 6.5, bottom: 6.5),
                        color: const Color(0xFF4B4A4D),
                        width: 1,
                      ),
                      GestureDetector(
                        onTap: () {
                          EasyLoading.show(status: '请稍等...');
                          APIServer()
                              .clickLike(
                                  record.id ?? 0, record.isLike == 0 ? 1 : 0)
                              .then((value) {
                            EasyLoading.dismiss();

                            record.isLike = record.isLike == 0 ? 1 : 0;

                            setState(() {});
                          }).onError((error, stackTrace) {
                            EasyLoading.dismiss();
                            showErrorMessage(resolveError(context, error!));
                          });
                        },
                        child: Container(
                            color: Colors.transparent,
                            width: 40,
                            height: 30,
                            child: Center(child: imgWidget(17, 17, record.isLike == 0 ? 'zan' : 'yizan'))),
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 6.5, bottom: 6.5),
                        color: const Color(0xFF4B4A4D),
                        width: 1,
                      ),
                      GestureDetector(
                        onTap: () {

                          showCustomTipsDialog(context, '删除收藏', '是否删除该收藏内容', onSubmit: (diaContext) {

                            EasyLoading.show(status: '请稍等...');
                            APIServer()
                                .clickCollect(
                                record.id ?? 0, record.isCollect == 0 ? 1 : 0)
                                .then((value) {
                              diaContext.pop();
                              EasyLoading.dismiss();

                              // record.isCollect = record.isCollect == 0 ? 1 : 0;

                              _refreshController.requestRefresh();
                            }).onError((error, stackTrace) {
                              diaContext.pop();
                              EasyLoading.dismiss();
                              showErrorMessage(resolveError(context, error!));
                            });
                          });
                        },
                        child: Container(
                            color: Colors.transparent,
                            padding: const EdgeInsets.only(left: 2),
                            width: 45,
                            height: 30,
                            child: Center(
                              child: imgWidget(
                                  17,
                                  17,
                                  record.isCollect == 0
                                      ? 'collection0'
                                      : 'collection1'),
                            )),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ]);
  }

  /// 构建消息框
  Widget _buildMessageBox(
    BuildContext context,
    CollectionRecord record,
  ) {
    var text = record.content.replaceAll('\\n', '\\\n');

    // 普通消息
    return Align(
      alignment: Alignment.topLeft,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: _chatBoxMaxWidth(context)),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: const EdgeInsets.fromLTRB(12, 6, 12, 6),
              child: ConstrainedBox(
                constraints: BoxConstraints(
                  maxWidth: _chatBoxMaxWidth(context) - 15 * 2,
                  // maxHeight: 165,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    MyTextSingle(text.trim(), 15, Colors.white, FontWeight.normal, maxLines: 7),
                    Visibility(
                      visible: textExceedMaxLines(text.trim(), const TextStyle(fontSize: 15, fontWeight: FontWeight.normal), 7, _chatBoxMaxWidth(context) - 15 * 2 - 12 * 2),
                      child: MyTextSingle('...', 15, Colors.white, FontWeight.normal),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  bool textExceedMaxLines(String text, TextStyle textStyle, int maxLine, double maxWidth) {
    TextSpan textSpan = TextSpan(text: text, style: textStyle);
    TextPainter textPainter = TextPainter(text: textSpan, maxLines: maxLine, textDirection: TextDirection.ltr);
    textPainter.layout(maxWidth: maxWidth);
    if (textPainter.didExceedMaxLines) {
      return true;
    }
    return false;
  }

  /// 获取聊天框的最大宽度
  double _chatBoxMaxWidth(BuildContext context) {
    var screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth >= CustomSize.maxWindowSize) {
      return CustomSize.maxWindowSize;
    }

    return screenWidth;
  }

  void _getCollectList() {
    APIServer().queryCollectList(page).then((value) {
      if (page == 1) {
        _refreshController.refreshCompleted();
        items.clear();
      } else {
        _refreshController.loadComplete();
      }
      if ((value.records?.length ?? 0) > 0) {
        items.addAll(value.records ?? []);
      }

      var total = value.total ?? 0;
      if (total >= items.length) {
        // _refreshController.loadNoData();
      }
      setState(() {});
    });
  }

}

///空列表背景
Widget NullListWidget(String img, String content) {
  return Container(
    width: double.maxFinite,
    height: double.maxFinite,
    color: Colors.transparent,
    child: Column(
      mainAxisAlignment:MainAxisAlignment.center,
      children: <Widget>[
        Container(
          margin: const EdgeInsets.only(bottom: 16),
          child: Image(
            width: 180,
            height: 180,
            image: AssetImage(img),
          ),
        ),
        MyText(content, 16, Colors.white.withOpacity(0.7)),
        SizedBox(height: 80.w),
      ],
    ),
  );
}